package com.mall.controller;

import com.mall.common.model.GlobalResponse;
import com.mall.consts.MallConst;
import com.mall.form.CartAddForm;
import com.mall.form.CartUpdateForm;
import com.mall.pojo.User;
import com.mall.service.ICartService;
import com.mall.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @Classname CartController
 * @Description
 * @Date 2022/7/30 13:56
 * @Created by TaoVh
 */
@RestController
public class CartController {
    ICartService cartService;

    @Autowired
    public void setCartService(ICartService cartService) {
        this.cartService = cartService;
    }


    @GetMapping("/carts")
    public GlobalResponse<CartVO> list(HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.list(user.getId());
    }

    @PostMapping("/carts")
    public GlobalResponse<CartVO> add(@Valid @RequestBody CartAddForm cartAddForm,
                                      HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        Integer uid = user.getId();
        return cartService.add(uid, cartAddForm);
    }

    @PutMapping("/carts/{productId}")
    public GlobalResponse<CartVO> update(@PathVariable Integer productId,
                                         @Valid @RequestBody CartUpdateForm form,
                                         HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.update(user.getId(), productId, form);
    }

    @DeleteMapping("/carts/{productId}")
    public GlobalResponse<CartVO> add(@PathVariable Integer productId, HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.delete(user.getId(), productId);
    }

    @PutMapping("/carts/selectAll")
    public GlobalResponse<CartVO> selectAll(HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.selectAll(user.getId());
    }

    @PutMapping("/carts/unSelectAll")
    public GlobalResponse<CartVO> unselectAll(HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.unselectAll(user.getId());
    }

    @GetMapping("/carts/products/sum")
    public GlobalResponse<Integer> sum(HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return cartService.sum(user.getId());
    }
}
